// Package service @program: gateway
//@author: edte
//@create: 2021-12-29 09:24
package service

import (
	"gateway/client/account"
	"gateway/tools/user"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

type userLogin struct {
	UserNum  string
	Password string
}

func UserLogin(ct *gin.Context) {
	json := userLogin{}
	err := ct.BindJSON(&json)
	// 如果接收到的json文件为空则拒绝下一步操作
	if err != nil || json.UserNum == "" || json.Password == "" {
		ct.JSON(http.StatusBadRequest, gin.H{"status": http.StatusBadRequest, "message": "请求格式不对"})
		return
	}
	loginServer, err := account.UserLoginClient(json.UserNum, json.Password)
	if err != nil {
		log.Println(err)
		ct.JSON(http.StatusBadRequest, loginServer)
		return
	}
	ct.JSON(http.StatusOK, loginServer)
}

type userRegister struct {
	Id          int    `gorm:"primaryKey"`
	UserPhone   string `gorm:"unique"`
	Password    string
	EmailNumber string
	NickName    string
	Status      bool
}

func UserRegister(ct *gin.Context) {
	json := userRegister{}
	err := ct.BindJSON(&json)
	// 如果接收到的json文件为空则拒绝下一步操作
	if err != nil || json.UserPhone == "" || json.Password == "" {
		ct.JSON(http.StatusBadRequest, gin.H{"status": http.StatusBadRequest, "message": "请求格式不对"})
		return
	}

	client, err := account.UserRegisterClient(json.UserPhone, json.Password, json.EmailNumber, json.NickName)
	if err != nil {
		log.Println(err)
		ct.JSON(http.StatusBadRequest, client)
		return
	}
	ct.JSON(http.StatusOK, client)
}

func UserUpdate(ct *gin.Context) {
	json := user.UpdateJson{}
	err := ct.BindJSON(&json)
	// 如果接收到的json文件为空则拒绝下一步操作
	if err != nil || json.Phone == "" || json.OldPassword == "" {
		ct.JSON(http.StatusBadRequest, gin.H{"status": http.StatusBadRequest, "message": "请求格式不对"})
		return
	}
	update, err := account.UserUpdate(json)
	if err != nil {
		log.Println(err)
		ct.JSON(http.StatusBadRequest, update)
		return
	}

	ct.JSON(http.StatusOK, update)
}

type userquery struct {
	Token string
}

func UserQuery(ct *gin.Context) {
	json := userquery{}
	err := ct.BindJSON(&json)
	if err != nil || json.Token == "" {
		ct.JSON(http.StatusBadRequest, gin.H{"status": http.StatusBadRequest, "message": "请求格式不对"})
		return
	}
	data, err := account.UserQueryData(json.Token)
	if err != nil {
		log.Println(err)
		ct.JSON(http.StatusBadRequest, data)
		return
	}
	ct.JSON(http.StatusOK, data)
}
